package com.yf.aclient.threads;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import com.yf.aclient.util.NumberUtil;
/***
 * 
 * 通过资源ID从服务器内部通过向输出流写字节的形式，下载资源的代码。。
 * @author yufei
 *
 */
public class DownldThread extends Thread {
	private  String fileName;
	private InputStream inputStream;
	private OutputStream outputStream;
	private Handler  handler;
	private HttpResponse response;
	private Long id;
	private String serverUrl;
	/***
	 * 
	 * @param serverUrl  服务器地址。。
	 * @param id  要下载的资源id 
	 * @param fileName 要下载的文件名称
	 * @param handler
	 */
	public DownldThread(String serverUrl,Long id,String fileName,Handler handler){
		this.fileName=fileName;
		this.handler=handler;
		this.id=id;
		this.serverUrl=serverUrl;
	}
	public void  run(){
		try{
			download(fileName);
		}catch(Exception e){
			e.printStackTrace();
		}
	//	this.stop();
	}
	//android.content.res.Resources$NotFoundException: String resource ID #0x1
	private void download(String fileName){
            /*
	         * 连接到服务器
	         */
		String getRolesUrl = this.serverUrl+"/task/downLoadResource.action";
		HttpPost request = new HttpPost(getRolesUrl);
		try {
			StringEntity reqEntity;
			reqEntity = new StringEntity("id="+id);
			reqEntity.setContentType("application/x-www-form-urlencoded");
			request.setEntity(reqEntity);
			HttpClient client=new DefaultHttpClient();
			response = client.execute(request);
			inputStream=response.getEntity().getContent();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	        /*
	         * 文件的保存路径如果不存在则新建
	          */
           String savePath=Environment.getExternalStorageDirectory()+"/Download";
            File file1=new File(savePath);
    	        if (!file1.exists()) {
   	            file1.mkdir();
            }
//    	  String fileName=downloadUrl.substring(downloadUrl.lastIndexOf("/")+1, downloadUrl.length());
          String filePathStr=savePath+"/"+fileName;
	      File file =new File(filePathStr);
		        if (!file.exists()) {
		            try {
		                file.createNewFile();
	            } catch (IOException e) {
	              // TODO Auto-generated catch block
	                e.printStackTrace();
	           }  
	      }
		        /*
		        * 向SD卡中写入文件,用Handle传递线程
		        */
	        Message message=Message.obtain();
        try {
           outputStream=new FileOutputStream(file);
	       byte [] buffer=new byte[1024];
          // Long fileLength=response.getEntity().getContentLength();
	       HttpEntity entity = response.getEntity();
           int fileLength = (int)entity.getContentLength();
           double  downloadedLength=0;
           message.what=0;
           message.obj="开始下载";
	       handler.sendMessage(message);
           int   perSize=0;
           double   reportSize=fileLength*0.1;

           int len = 0;   
           while( (len=inputStream.read(buffer)) != -1){ 
    	       perSize+=len;
    	       downloadedLength+=len;
    	       if(perSize>reportSize){
    	    	   perSize=0;
   	        	double p=downloadedLength/fileLength;
   	            Message message2=new Message();
	            message2.obj="已下载："+NumberUtil.convertNumbertoString(0, p*100)+"%";
	            message2.what=0;
	            handler.sendMessage(message2);
    	       }
        	   outputStream.write(buffer, 0, len);  
           }
	            Message message2=new Message();
	            message2.obj="{\"info\":\"下载完成!\",\"fileName\":\""+fileName+"\"}";
	            message2.what=1;
	            handler.sendMessage(message2);
        } catch (FileNotFoundException e) {
        	Message message3=new Message();
             message3.obj="下载失败！";
             message3.what=0;
            handler.sendMessage(message3);
	            e.printStackTrace();
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	        	Message message4=new Message();
	             message4.obj="下载失败！";
	             message4.what=0;
	             handler.sendMessage(message4);
            e.printStackTrace();
        }
	}
}
